package com.xunua.NaoZiKongBai.Fragments;

import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.gyf.immersionbar.ImmersionBar;
import com.tencent.mmkv.MMKV;
import com.trello.rxlifecycle2.components.support.RxFragment;
import com.xunua.NaoZiKongBai.Bean.Bmob.MyUser;
import com.xunua.NaoZiKongBai.Bean.EventBus.UpdatePwdEvent;
import com.xunua.NaoZiKongBai.Bean.EventBus.UpdateUserInfoEvent;
import com.xunua.NaoZiKongBai.Bean.EventBus.WoDeRefreshEvent;
import com.xunua.NaoZiKongBai.LoginActivity.LoginActivity;
import com.xunua.NaoZiKongBai.MyApplication;
import com.xunua.NaoZiKongBai.R;
import com.xunua.NaoZiKongBai.UpdateUserInfoActivity.UpdateUserInfoActivity;
import com.xunua.NaoZiKongBai.Utils.log;
import com.xunua.NaoZiKongBai.View.RoundImageView;
import com.xunua.NaoZiKongBai.View.UpdatePwdPopup;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.ByteArrayInputStream;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FetchUserInfoListener;
import cn.bmob.v3.listener.UpdateListener;

public class WoDeFragment extends RxFragment {
    @BindView(R.id.wode_icon)
    RoundImageView wodeIcon;
    @BindView(R.id.wode_nickname)
    TextView wodeNickname;
    @BindView(R.id.wode_statur)
    TextView wodeStatur;
    @BindView(R.id.wode_line_userinfo)
    LinearLayout wodeLineUserinfo;
    @BindView(R.id.wode_refresh)
    SwipeRefreshLayout wodeRefresh;
    @BindView(R.id.wode_line_more)
    LinearLayout wodeLineMore;
    @BindView(R.id.wode_scrollview)
    ScrollView wodeScrollview;
    @BindView(R.id.wode_update_img)
    ImageView wodeUpdateImg;
    @BindView(R.id.wode_line_update)
    LinearLayout wodeLineUpdate;
    @BindView(R.id.wode_resetpwd_img)
    ImageView wodeResetpwdImg;
    @BindView(R.id.wode_line_resetpwd)
    LinearLayout wodeLineResetpwd;
    @BindView(R.id.wode_logout_img)
    ImageView wodeLogoutImg;
    @BindView(R.id.wode_line_logout)
    LinearLayout wodeLineLogout;
    @BindView(R.id.wode_parent_line)
    LinearLayout wodeParentLine;
    private Unbinder unbinder;

    private MMKV mmkv = MMKV.mmkvWithID("user_icon",MMKV.MULTI_PROCESS_MODE);


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_wo_de, container, false);
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        fetchUserInfo();
        setWodeRefreshListener();
        initIcon();
    }

    private void initIcon() {
        final byte[] icons = mmkv.getBytes("icon", null);
        if (icons != null) {
            final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(icons);
            wodeIcon.setImageBitmap(BitmapFactory.decodeStream(byteArrayInputStream));
        }
    }

    private void setWodeRefreshListener() {
        wodeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //设置为刷新状态并不会触发此监听。   只有手动下滑才会触发此监听
                fetchUserInfo();
            }
        });
    }

    /**
     * 同步控制台数据到缓存中
     */
    public synchronized void fetchUserInfo() {
        BmobUser.fetchUserInfo(new FetchUserInfoListener<BmobUser>() {
            @Override
            public void done(BmobUser user, BmobException e) {
                if (e == null) {
                    //更新成功
                    MyUser myUser = BmobUser.getCurrentUser(MyUser.class);
                    wodeNickname.setText(myUser.getNick_name());
                } else {
                    //更新失败
                }
                wodeRefresh.setRefreshing(false);
            }
        });
    }

    private void initStatur() {
        ImmersionBar.with(this)
                .statusBarView(wodeStatur)
                .keyboardEnable(false)//解决软键盘与底部输入框冲突问题
                .statusBarDarkFont(false)//状态栏字体颜色
                .navigationBarColor(R.color.navigationBarcolor)//导航栏颜色，不写默认黑色
                .navigationBarDarkIcon(true)//导航栏图标是深色，不写默认为亮色
                .init();//沉浸状态栏
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            initStatur();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setWodeRefreshListener(WoDeRefreshEvent event) {
        if (!wodeRefresh.isRefreshing()) {
            wodeRefresh.setRefreshing(true);
            fetchUserInfo();
        }
    }

    @OnClick({R.id.wode_line_update, R.id.wode_line_resetpwd, R.id.wode_line_logout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.wode_line_update://修改信息
                startActivity(new Intent(getContext().getApplicationContext(),UpdateUserInfoActivity.class));
                break;
            case R.id.wode_line_resetpwd://修改密码
                UpdatePwdPopup updatePwdPopup = new UpdatePwdPopup(getContext());
                View updateview = updatePwdPopup.getContentView();
                EditText etoldpwd=updateview.findViewById(R.id.updatepwd_et_oldpwd);
                EditText etnewpwd=updateview.findViewById(R.id.wode_updatepwd_et_newpwd);
                EditText etrelnewpwd=updateview.findViewById(R.id.wode_updatepwd_et_relupdatepwd);
                TextView tvinfo=updateview.findViewById(R.id.wode_updatepwd_tv_info);
                Button btnupdate=updateview.findViewById(R.id.wode_update_btn_update);
                Button btncancel=updateview.findViewById(R.id.wode_update_btn_cancel);
                updatePwdPopup.setOutSideDismiss(false);
                updatePwdPopup.setBlurBackgroundEnable(true);
                ScaleAnimation scaleAnimation = new ScaleAnimation(0, 1, 0, 1, Animation.RELATIVE_TO_PARENT, 0.5f, Animation.RELATIVE_TO_PARENT, 0.5f);
                scaleAnimation.setDuration(500);
                updatePwdPopup.setShowAnimation(scaleAnimation);
                ScaleAnimation scaleAnimationdismiss = new ScaleAnimation(1, 0, 1, 0, Animation.RELATIVE_TO_PARENT, 0.5f, Animation.RELATIVE_TO_PARENT, 0.5f);
                scaleAnimationdismiss.setDuration(500);
                updatePwdPopup.setDismissAnimation(scaleAnimationdismiss);
                updatePwdPopup.showPopupWindow();
                btnupdate.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String oldpwd = etoldpwd.getText().toString().trim();
                        String newpwd = etnewpwd.getText().toString().trim();
                        String relnewpwd = etrelnewpwd.getText().toString().trim();
                        if (newpwd.length() < 8 || relnewpwd.length() < 8) {
                            tvinfo.setText("请输入8-18位密码");
                            tvinfo.setVisibility(View.VISIBLE);
                        } else if (oldpwd.equals(newpwd) && oldpwd.equals(relnewpwd)) {
                            tvinfo.setText("新旧密码重复");
                            tvinfo.setVisibility(View.VISIBLE);
                        } else {
                            if (newpwd.equals(relnewpwd)) {
                                tvinfo.setVisibility(View.GONE);
                                tvinfo.setText("");
                                hideKeyBord(updateview);
                                updatePwdPopup.dismiss();
                                EventBus.getDefault().post(new UpdatePwdEvent(oldpwd, newpwd));
                            } else {
                                //两次确认密码一致  告知activity进行用户密码修改
                                tvinfo.setText("两次输入密码不一致");
                                tvinfo.setVisibility(View.VISIBLE);
                            }
                        }
                    }
                });
                btncancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        hideKeyBord(updateview);
                        updatePwdPopup.dismiss();
                    }
                });
                break;
            case R.id.wode_line_logout://退出登录
                MyApplication application = (MyApplication) getActivity().getApplication();
                application.finishAllActivity();
                Intent intent = new Intent(application, LoginActivity.class);
                BmobUser.logOut();//清除当前登录用户
                startActivity(intent);
                break;
        }
    }
    private void hideKeyBord(View view){//这个view我传的是popwindow的view
        InputMethodManager inputMgr = (InputMethodManager) getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMgr.hideSoftInputFromWindow(view.getWindowToken(),0);//这个是隐藏输入法
//        inputMgr.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS, 0);//这个是输入法切换，当输入法显示了就隐藏输入法，当输入法隐藏了就显示.
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void UpdateUserInfoEvent(UpdateUserInfoEvent event){
        initIcon();
        final String nick_name = event.getNick_name()==null?"":event.getNick_name();
        final String rel_name = event.getRel_name()==null?"":event.getRel_name();
        //由于bmob的文件上传需要绑定域名，本来是上传base64的，但是失策了,bmob后台接收这么一长串字符会出问题
        final MyUser myUser = BmobUser.getCurrentUser(MyUser.class);
        if (!(myUser.getNick_name().equals(nick_name)&&myUser.getReal_name().equals(rel_name))){
            if (!nick_name.equals(""))
            myUser.setNick_name(nick_name);
            if (!rel_name.equals(""))
            myUser.setReal_name(rel_name);

            myUser.update(myUser.getObjectId(),new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        //更新成功
                        wodeRefresh.setRefreshing(true);
                        fetchUserInfo();
                        //修改成功
                        Toast.makeText(getContext(), "个人信息修改成功", Toast.LENGTH_SHORT).show();
                        return;
                    }else {
                        //修改失败
                        Toast.makeText(getContext(), "个人信息修改失败", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }
}
